package com.pudu.pudusclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pudu.mydemo.fragment.DiagramFragment;
import com.pudu.mydemo.utils.ConstantUtils;
import com.pudu.pdrobot.App;
import com.pudutech.pdrobot.R;

import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Arrays;

public class ServerAct extends Activity {


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try{
			this.unbindService(serviceConnection);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public static ServerSocket serverSocket = null;

	public static TextView mTextViewStatus, textViewShowIP;
	public ListView lvWifiReceive,lvUsbReceive;
	public Button mBtnControl, mShowMap;
	public ControlServiceService myService;

    public static ArrayAdapter<String> adapterCAN;
    public static ArrayAdapter<String> adapterWifi;
    public static ArrayList<String> canData = new ArrayList<String>();
    public static ArrayList<String> wifiData = new ArrayList<String>();

	private String IP = "";
	String buffer = "";
	private int nServiceRunning  = 0; //0 stop , 1 start, 2 connected
    private boolean isStop = false;

	public static Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0x11) {
				Bundle bundle = msg.getData();
				mTextViewStatus.append("client" + bundle.getString("msg") + "\n");
			}
			if(msg.what == 0x12){
				try {
					byte[] objData = (byte[]) msg.obj;
					wifiData.add(Arrays.toString(objData));
					if(wifiData.size() > 30)
						wifiData.remove(1);
					adapterWifi.notifyDataSetChanged();
				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			if (msg.what == 0x13) {
				try {
					byte[] objData = (byte[]) msg.obj;
					canData.add(Arrays.toString(objData));
					if(canData.size() > 30)
						canData.remove(1);
					adapterCAN.notifyDataSetChanged();
				}catch(Exception e)
				{
					e.printStackTrace();
				}
			}
			if (msg.what == 0x14) {
				String string = (String)msg.obj;
				Toast.makeText(App.context(), string, Toast.LENGTH_SHORT).show();
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.debug_activity_socket);

//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);

		mTextViewStatus = (TextView) findViewById(R.id.tvServiceStatus);
		textViewShowIP = (TextView) findViewById(R.id.tvShowip);

        lvUsbReceive = (ListView) findViewById(R.id.lvUsbReceive);
		lvWifiReceive = (ListView) findViewById(R.id.lvWifiReceive);
		canData.add("CAN数据:");
		wifiData.add("WIFI数据:");
        adapterCAN = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, canData);
        adapterWifi = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,wifiData);
        lvUsbReceive.setAdapter(adapterCAN);
        lvWifiReceive.setAdapter(adapterWifi);

		IP = getlocalip();
		textViewShowIP.setText("IP addresss:" + IP + ":" + ControlServiceService.SERVERPORT);
		mBtnControl = (Button) findViewById(R.id.button1);
		mShowMap = (Button)findViewById(R.id.showMap);
		mBtnControl.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Log.i(App.MYTAG, "" + nServiceRunning);
				if( nServiceRunning == 0)
				{
					StartServiceListen();
					mTextViewStatus.setText(R.string.control_service_status_start);
					mBtnControl.setText(R.string.control_service_stop);
					nServiceRunning = 2;
				}
				else if( nServiceRunning == 2)
				{
					StopServiceListen();
					mTextViewStatus.setText(R.string.control_service_status_stop);
					mBtnControl.setText(R.string.control_service_start);
					nServiceRunning = 0;
				}
			}});

		mShowMap.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DiagramFragment diagramFragment = new DiagramFragment();
				diagramFragment.show(getFragmentManager(),"diagramFragment2");
			}
		});

		StartControlService();
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i(App.MYTAG,"onResume");
		initStatus();
	}

	public void initStatus()
	{
		Log.i(App.MYTAG,"initStatus");
		if( ControlServiceService.mServiceRunning == true)
		{
			mTextViewStatus.setText(R.string.control_service_status_start);
			mBtnControl.setText(R.string.control_service_stop);

			Intent bindingIntent = new Intent(this, ControlServiceService.class);
			bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
			nServiceRunning = 2;
		}
		else
		{
			mTextViewStatus.setText(R.string.control_service_status_stop);
			mBtnControl.setText(R.string.control_service_start);
			nServiceRunning = 0;
		}
	}

	public void StartControlService()
	{
		Intent bindingIntent = new Intent(this, ControlServiceService.class);
		startService(bindingIntent);
		bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
	}

	public void StartServiceListen()
	{
		App.getInstance().myService.StartSocketWork();
	}
	public void StopServiceListen()
	{
		Log.i(App.MYTAG, "StopService");
		//this.unbindService(serviceConnection);
		//Intent bindingIntent = new Intent(ServerAct.this, ControlServiceService.class);
		//ServerAct.this.stopService(bindingIntent);

		App.getInstance().myService.StopSocketWork();

	}

	//wifi数据回调
	ControlServiceService.respondCallback mCallback = new ControlServiceService.respondCallback(){
		@Override
		public byte[] OnReceive(byte [] data) {
			Message msg = mHandler.obtainMessage();
			msg.obj = data;
			msg.what = 0x12;
			mHandler.sendMessage(msg);

			return data;
		}
	};


	//can口的回调
	ControlServiceService.canCallback mCANCallback = new ControlServiceService.canCallback(){
		@Override
		public byte[] OnReceive(byte[] data) {
			Message msg = mHandler.obtainMessage();
			msg.obj = data;
			msg.what = 0x13;
			mHandler.sendMessage(msg);

			return data;
		}
	};

	private final ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			App.instance.myService = ((ControlServiceService.ServiceBinder) service).getService();
			App.instance.myService.SetReceiveCallback(mCallback);
			App.instance.myService.setcanCallback(mCANCallback);

			Log.i(App.MYTAG, "onServiceConnected");
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			//onServiceDisconnected is only called in extreme situations (crashed / killed).
			Log.i(App.MYTAG, "onServiceDisconnected");
		}

	};

	/**
	 * 或取本机的ip地址
	 */
	private String getlocalip() {
		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		ConstantUtils.IP_STRING = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
				+ (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
		Log.i("lgq", "int ip "+ConstantUtils.IP_STRING);
		if (ipAddress == 0)
			return null;
		return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "."
				+ (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
	}

}
